import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:xrenovation/services/theme_service.dart';

class ThemeSwitcher extends StatefulWidget {
  const ThemeSwitcher({super.key});

  @override
  State<ThemeSwitcher> createState() => _ThemeSwitcherState();
}

class _ThemeSwitcherState extends State<ThemeSwitcher> with SingleTickerProviderStateMixin {
  late AnimationController _controller;

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final isDark = theme.brightness == Brightness.dark;

    // 确保动画状态与当前主题一致
    if (isDark && _controller.value != 1) {
      _controller.forward();
    } else if (!isDark && _controller.value != 0) {
      _controller.reverse();
    }

    return Tooltip(
      message: isDark ? 'Switch to light mode' : 'Switch to dark mode',
      child: IconButton(
        iconSize: 24,
        padding: const EdgeInsets.all(8),
        constraints: const BoxConstraints(minWidth: 48, minHeight: 48),
        icon: RotationTransition(
          turns: _controller,
          child: Icon(isDark ? Icons.dark_mode : Icons.light_mode, color: theme.colorScheme.onSurface),
        ),
        // icon: AnimatedSwitcher(
        //   duration: const Duration(milliseconds: 300),
        //   transitionBuilder: (Widget child, Animation<double> animation) {
        //     return ScaleTransition(scale: animation, child: child);
        //   },
        //   child: Icon(
        //     isDark ? Icons.dark_mode : Icons.light_mode,
        //     key: ValueKey<bool>(isDark),
        //     color: theme.colorScheme.onSurface,
        //   ),
        // ),
        onPressed: _toggleTheme,
      ),
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(vsync: this, duration: const Duration(milliseconds: 300));
  }

  void _toggleTheme() {
    final themeService = Provider.of<ThemeService>(context, listen: false);
    final newThemeMode = Theme.of(context).brightness == Brightness.dark ? ThemeMode.light : ThemeMode.dark;

    themeService.setThemeMode(newThemeMode);

    // 提供触觉反馈
    Feedback.forTap(context);
  }
}
